//
//  NYMyVipViewController.m
//  NiuWaJiaoYu
//
//  Created by MinLison on 2018/1/9.
//  Copyright © 2018年 niuwaketang. All rights reserved.
//

#import "NYMyVipViewController.h"
#import "NYMyVipRequest.h"
#import "NYMyVipTitleSectionHeader.h"
#import "NYMyVipBuyCell.h"
#import "NYMyVipPrivilegeCell.h"

#import "NYVIPListRequest.h"
#import "NYExchangeMemberRequest.h"

#import "PayManager.h"
#import "NYIAPValidationRequest.h"

@interface NYMyVipViewController ()

@end

@implementation NYMyVipViewController
- (void)presentOrPushInViewController:(UIViewController *)viewController
{
        
        if (viewController.navigationController)
        {
                if ([viewController.navigationController.viewControllers.lastObject isKindOfClass:[NYMyVipViewController class]]) {
                        return;
                }
                [viewController.navigationController pushViewController:self animated:YES];
        }
        else
        {
                if ([viewController.presentedViewController isKindOfClass:[BaseNavigationViewController class]])
                {
                        BOOL res = [[(BaseNavigationViewController *)viewController.presentedViewController viewControllers].lastObject isKindOfClass:[NYMyVipViewController class]];
                        if (res)
                        {
                                return;
                        }
                }
                BaseNavigationViewController *nav = [[BaseNavigationViewController alloc] initWithRootViewController:self];
                [viewController presentViewController:nav animated:YES completion:nil];
        }
}
- (void)viewDidLoad
{
        [super viewDidLoad];
        [self loadData];
}
- (void)configNimbus
{
        [super configNimbus];
        [self.tableView registerClass:[NYMyVipTitleSectionHeader class] forHeaderFooterViewReuseIdentifier:[NYMyVipTitleSectionHeader className]];
        [self.tableView registerClass:[BaseTableHeaderFooterView class] forHeaderFooterViewReuseIdentifier:[BaseTableHeaderFooterView className]];
}
- (void)loadData
{
        [self loadDataWithAnimation:YES];
}
- (void)loadDataWithAnimation:(BOOL)animation
{
        @weakify(self);
        [self configNimbus];
        if (animation) {
                [self setLoading:animation animation:animation];
        }
        [[NYMyVipRequest requestWithParams:nil] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYMyVipModel * _Nonnull data) {
                
                @strongify(self);
                self.controllerView.headerView.vipModel = data;
                [self configNimbusData];
                [self setSuccess];
        } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                [self setError:error];
        }];
        
        [[NYVIPListRequest requestWithParams:nil] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NSArray<NYVipPayModel *> * _Nonnull data) {
                
                @strongify(self);
                [self.tableViewModel addObjectsFromArray:data];
                [self.tableViewModel addSectionWithTitle:nil];
                [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYMyVipPrivilegeCell class] userInfo:nil]];
                [self.tableView reloadData];
                [self setSuccess];
        } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
        }];
}
- (void)configNimbusData
{
        [self.tableView reloadData];
//        [self.tableViewModel addObjectsFromArray:[NYPurchaseUIManager getVipList]];
}


- (UITableViewCell *)tableViewModel:(NITableViewModel *)tableViewModel cellForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
        
        UITableViewCell *cell = [super tableViewModel:tableViewModel cellForTableView:tableView atIndexPath:indexPath withObject:object];
        if ([cell isKindOfClass:[NYMyVipBuyCell class]]) {
                [self configActionCell:(NYMyVipBuyCell *)cell];
        }
        return cell;
}
- (void)configActionCell:(NYMyVipBuyCell *)actionCell {
        
        @weakify(self);
        [actionCell setActionBlock:^(NYVipPayModel *vipModel) {
                
                //点击开通、调用支付
                @strongify(self);
//                [self exchangeVIPMember:vipModel.id];
                [NYTipClass showLoadingInView:self.view];
                
                void(^PayCallBackBlock)(NSArray *content, NSError *error, VerifyReceiptCompletion completion) = ^(NSArray *content, NSError *error, VerifyReceiptCompletion completion) {
                        if (!error && content) {
                                //向服务器验证
                                NSString *timeSp = [NSString stringWithFormat:@"no%ld", (long)[[NSDate date] timeIntervalSince1970]];
                                [[NYIAPValidationRequest requestWithParams:@{
                                                                             kRequestReceipt : [content firstObject],
                                                                             kRequestTransactionId : timeSp,
                                                                             kRequestNum : NOT_NULL_STRING_DEFAULT_EMPTY(vipModel.price),
                                                                             kRequestKeyUser_ID : NOT_NULL_STRING_DEFAULT_EMPTY(NYUserManager.user_id),
                                                                             kRequestKeyLoginCode : NOT_NULL_STRING_DEFAULT_EMPTY(NYUserManager.logincode),
                                                                             }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof id  _Nonnull data) {
                                        
                                        [NYTipClass hideLoadingInView:self.view];
                                        [NYTipClass showText:request.tipString inView:self.view];
                                        [self loadDataWithAnimation:NO];
                                        if (completion) {
                                                completion(nil);
                                        }
                                } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                                        [NYTipClass hideLoadingInView:self.view];
                                        [NYTipClass showText:error.localizedDescription inView:self.view];
                                        [self loadDataWithAnimation:NO];
                                        if (completion) {
                                                completion(error);
                                        }
                                }];
                        } else {
                                @weakify(self);
                                if (error.code == PayiTunesErrorCodeRestore) {
                                        [NYTipClass showLoadingInView:self.view];
                                } else {
                                        [NYTipClass showText:error.localizedDescription inView:self.view].didHideBlock = ^(UIView *hideInView, BOOL animated) {
                                                @strongify(self);
                                                [self loadDataWithAnimation:NO];
                                        };
                                        if (completion) {
                                                completion(error);
                                        }
                                }
                                
                        }
                        
                };
                
                if (vipModel.isBuyed) {
                        [[PayManager manager] restore:vipModel.goodId completion:PayCallBackBlock];
                } else {
                        [[PayManager manager] payItunes:vipModel.goodId completion:PayCallBackBlock];
                }
        }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        if (section == 0) {
                return __WGHeight(50);
        }
        return __WGHeight(10);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
        if (section == 0) {
                NYMyVipTitleSectionHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[NYMyVipTitleSectionHeader className]];
                header.contentView.backgroundColor = [UIColor whiteColor];
                return header;
        }
        BaseTableHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[BaseTableHeaderFooterView className]];
        header.contentView.backgroundColor = UIColorHex(0xF2F1EF);
        return header;
}
- (void)configNavigationBar:(BaseNavigationBar *)navigationBar
{
        [super configNavigationBar:navigationBar];
        self.title = @"会员中心";
}
- (BOOL)forceEnableNavigationBarBackItem
{
        return YES;
}
+ (NYViewControllerNavigationBarType)navigationBarType
{
        return NYViewControllerNavigationBarTypeClear;
}

//MARK: 兑换会员
- (void)exchangeVIPMember:(NSString *)product_id {
        
        [NYTipClass showLoadingInView:self.view];
        [[NYExchangeMemberRequest requestWithParams:@{
                                                      kRequestProductID : NOT_NULL_STRING_DEFAULT_EMPTY(product_id),
                                                      kRequestKeyUser_ID : NOT_NULL_STRING_DEFAULT_EMPTY(NYUserManager.user_id),
                                                      kRequestKeyLoginCode : NOT_NULL_STRING_DEFAULT_EMPTY(NYUserManager.logincode),
                                                      }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof id  _Nonnull data) {
                
                [NYTipClass hideLoadingInView:self.view];
                [NYTipClass showText:request.tipString inView:self.view];
                [self loadData];
        } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                
                [NYTipClass hideLoadingInView:self.view];
                [NYTipClass showText:error.localizedDescription];
        }];
}

@end
